const apiPath = '/api/modules/'

const restApiPath = apiPath + 'ainmodule/rest/'
const fortuneApiPath = apiPath + 'ainmodule/fortune/'

// modules
async function getModules() {
	try {
		const response = await $.ajax({
			url: apiPath + 'get',
			type: 'GET',
		})
		const { code, msg, data } = response
		if (code !== 200) {
			showNotify(msg, 'danger', 5000, 'mdi mdi-alert', 'top', 'right')
			return
		}
		
		for (const key in data) {
			const val = data[key]
				, $input = $(`input[name="${key}"]`)
				, $textarea = $(`textarea[name="${key}"]`)
			if ($input.length > 0) {
				$input.val(val)
			}

			else if ($textarea.length > 0) {
				$textarea.val(val)
			}

			else {
				console.warn('暂无匹配')
				continue
			}
		}
	} catch (error) {
		showNotify('服务器有误', 'danger', 5000, 'mdi mdi-alert', 'top', 'right')
		console.log(error)
	}
}

async function setModules(e, array) {
	e.preventDefault()

	if (array.length < 0) {
		showNotify('参数不得为空', 'info', 5000, 'mdi mdi-alert', 'top', 'right')
		return
	}

	const formArrayInfo = $(e.target).serializeArray()
	let batchData = []
	
	$.each(formArrayInfo, function (_index, item) {
		batchData.push({
			module: item.name,
			xf_values: item.value || null
		})
	})

	const size = batchData.length - 1
	
	batchData.forEach(async (item, i) => {
		const jsonStr = JSON.stringify(item)
		
		try {
			const response = await $.ajax({
				url: apiPath + 'set',
				type: 'POST',
				data: jsonStr,
				contentType: 'application/json'
			})
	
			const { code, msg } = response
			
			if (code !== 200) {
				showNotify(msg, 'info', 5000, 'mdi mdi-alert', 'top', 'right')
				return
			}

			if (i === size) {
				showNotify(msg, 'success', 5000, 'mdi mdi-emoticon-happy', 'top', 'right')
				return
			}
		} catch (error) {
			showNotify('服务器有误', 'danger', 5000, 'mdi mdi-alert', 'top', 'right')
			console.log(error)
		}
	})
}

// getList
async function getList(tableDom, api, callback) {
	tableDom.html('加载中...')
	try {
		const response = await $.ajax({
			url: api,
			type: 'GET',
			dataType: 'json'
		})

		const { code, msg, data } = response
		if (code !== 200) {
			showNotify(msg, 'danger', 5000, 'mdi mdi-alert', 'top', 'right')
			return
		}

		callback(data)

		// 渲染工具
		renderTooltip()
	} catch (error) {
		showNotify('服务器有误', 'danger', 5000, 'mdi mdi-alert', 'top', 'right')
		console.log(error)
	}
}

// delList
function delList(e, api, id) {
	const dom = $(e.target)
	
	$.confirm({
		title: `确定删除id为: ${id}的数据么`,
		content: '确定删除吗?',
		type: 'red',
		animation: 'scale',
		draggable: true,
		buttons: {
			'确定': {
				btnClass: 'btn-danger',
				action: function () {
					$.ajax({
						url: api + `del?id=${id}`,
						type: 'GET',
						success: function (response) {
							const { code, msg } = response
							if (code !== 200) {
								$.alert({
									title: '',
									content: msg,
									type: 'red'
								})
								return
							}

							$.alert({
								title: '',
								content: msg,
								type: 'green'
							})

							dom.parents('tr').remove()
						}
					})
				}
			},
			'取消': function () {}
		}
	})
}

/* rest */
async function getRest() {
	const $restTable = $('#restTable')

	await getList($restTable, restApiPath + 'get', data => {
		let tr = ''
		data.forEach(item => {
			tr += `
				<tr class="text-center align-middle">
					<td>${item.id}</td>
					<td>${item.text}</td>
					<td><img class="lazyload" data-src="${item.img}" style="height: 20px;"></td>
					<td>
						<div class="btn-group btn-group-sm">
							<a
								class="btn btn-default"
								href="JavaScript:;"
								data-bs-toggle="tooltip"
								title="编辑"
								onclick="setRest(${item.id}, '${item.text}', '${item.img}')"
							><i class="mdi mdi-pencil"></i></a>
							<a
								class="btn btn-default"
								href="JavaScript:;"
								data-bs-toggle="tooltip"
								title="移除"
								onclick="delList(event, '${restApiPath}', ${item.id})"
							><i class="mdi mdi-window-close"></i></a>
						</div>
					</td>
				</tr>
			`
		})
		$restTable.html(tr)

		$('.lazyload').lazyload({
			root: null,
			rootMargin: '100px',
			threshold: 0
		})
	})
}

function addRest() {
	$.confirm({
		title: '新增数据',
		type: 'blue',
		animation: 'scale',
		draggable: true,
		content: `
			<div class="form-group p-1 mb-0">
				<label class="control-label mb-1">文字</label>
				<div class="input-group">
					<input autofocus="" type="text" id="input-text" placeholder="请输入文字" class="form-control" autocomplete="off">
				</div>
			</div>
			<div class="form-group p-1 mb-0">
				<label class="control-label mb-1">网站图片</label>
				<div class="input-group">
					<input autofocus="" type="text" id="input-img" placeholder="请输入图标链接" class="form-control" autocomplete="off">
					<button class="btn btn-default uploadBtn" type="button"><span>上传图片</span><input type="file" accept="image/*" class="fileInput" onchange="handleFileSelect(event)"></button>
				</div>
			</div>
		`,
		buttons: {
			submit: {
				text: '提交',
				btnClass: 'btn-primary',
				action: function () {
					let that = this.$content

					const text = that.find('#input-text').val()
					const img = that.find('#input-img').val()

					const data = {
						text,
						img
					}
					if (!$.trim(text) || !$.trim(img)) {
						$.alert({
							title: '',
							content: '参数不得为空',
							type: 'orange'
						})
						return false
					}

					$.ajax({
						url: restApiPath + 'add',
						type: 'POST',
						data,
						success: function (response) {
							const { code, msg } = response
							if (code !== 200) {
								$.alert({
									title: '',
									content: msg,
									type: 'orange'
								})
								return
							}
							$.alert({
								title: '',
								content: '添加成功',
								type: 'green'
							})

							getRest()
						}
					})
				}
			},
			'取消': function () { }
		}
	})
}

function setRest(id, text, img) {
	$.confirm({
		title: '更新数据',
		type: 'blue',
		animation: 'scale',
		draggable: true,
		content: `
			<div class="form-group p-1 mb-0">
				<label class="control-label mb-1">文字</label>
				<div class="input-group">
					<input autofocus="" type="text" id="input-text" value="${text}" placeholder="请输入文字" class="form-control" autocomplete="off">
				</div>
			</div>
			<div class="form-group p-1 mb-0">
				<label class="control-label mb-1">网站图片</label>
				<div class="input-group">
					<input autofocus="" type="text" id="input-img" value="${img}" placeholder="请输入图标链接" class="form-control" autocomplete="off">
					<button class="btn btn-default uploadBtn" type="button"><span>上传图片</span><input type="file" accept="image/*" class="fileInput" onchange="handleFileSelect(event)"></button>
				</div>
			</div>
		`,
		buttons: {
			submit: {
				text: '提交',
				btnClass: 'btn-primary',
				action: function () {
					let that = this.$content

					const text = that.find('#input-text').val()
					const img = that.find('#input-img').val()

					const data = {
						id,
						text,
						img
					}
					if (!$.trim(id) || !$.trim(text) || !$.trim(img)) {
						$.alert({
							title: '',
							content: '参数不得为空',
							type: 'orange'
						})
						return false
					}

					$.ajax({
						url: restApiPath + 'set',
						type: 'POST',
						data,
						success: function (response) {
							const { code, msg } = response
							if (code !== 200) {
								$.alert({
									title: '',
									content: msg,
									type: 'orange'
								})
								return
							}
							$.alert({
								title: '',
								content: '更新成功',
								type: 'green'
							})

							getRest()
						}
					})
				}
			},
			'取消': function () { }
		}
	})
}

/* fortune */
async function getFortune() {
	const $fortuneTable = $('#fortuneTable')

	await getList($fortuneTable, fortuneApiPath + 'get', data => {
		let tr = ''
		data.forEach(item => {
			tr += `
				<tr class="text-center align-middle">
					<td>${item.id}</td>
					<td>${item.text}</td>
					<td>${item.width}%</td>
					<td>
						<div class="btn-group btn-group-sm">
							<a
								class="btn btn-default"
								href="JavaScript:;"
								data-bs-toggle="tooltip"
								title="编辑"
								onclick="setFortune(${item.id}, '${item.text}', '${item.width}')"
							><i class="mdi mdi-pencil"></i></a>
							<a
								class="btn btn-default"
								href="JavaScript:;"
								data-bs-toggle="tooltip"
								title="移除"
								onclick="delList(event, '${fortuneApiPath}', ${item.id})"
							><i class="mdi mdi-window-close"></i></a>
						</div>
					</td>
				</tr>
			`
		})
		$fortuneTable.html(tr)
	})
}

function addFortune() {
	$.confirm({
		title: '新增数据',
		type: 'blue',
		animation: 'scale',
		draggable: true,
		content: `
			<div class="form-group p-1 mb-0">
				<label class="control-label mb-1">文字</label>
				<div class="input-group">
					<input autofocus="" type="text" id="input-text" placeholder="请输入文字" class="form-control" autocomplete="off">
				</div>
			</div>
			<div class="form-group p-1 mb-0">
				<label class="control-label mb-1">运势百分比</label>
				<div class="input-group">
					<input autofocus="" type="number" id="input-width" placeholder="请输入数值" class="form-control" autocomplete="off">
					<span class="input-group-text"><i class="mdi mdi-percent-outline"></i></span>
				</div>
			</div>
		`,
		buttons: {
			submit: {
				text: '提交',
				btnClass: 'btn-primary',
				action: function () {
					let that = this.$content

					const text = that.find('#input-text').val()
					const width = that.find('#input-width').val()
					
					if (Number(width) < 0 || Number(width) > 100) {
						$.alert({
							title: '',
							content: '百分比不得小于0或大于100',
							type: 'orange'
						})
						return false
					}

					const data = {
						text,
						width
					}

					if (!$.trim(text) || !$.trim(width)) {
						$.alert({
							title: '',
							content: '参数不得为空',
							type: 'orange'
						})
						return false
					}

					$.ajax({
						url: fortuneApiPath + 'add',
						type: 'POST',
						data,
						success: function (response) {
							const { code, msg } = response
							if (code !== 200) {
								$.alert({
									title: '',
									content: msg,
									type: 'orange'
								})
								return
							}
							$.alert({
								title: '',
								content: '添加成功',
								type: 'green'
							})

							getFortune()
						}
					})
				}
			},
			'取消': function () { }
		}
	})
}

function setFortune(id, text, width) {
	$.confirm({
		title: '更新数据',
		type: 'blue',
		animation: 'scale',
		draggable: true,
		content: `
			<div class="form-group p-1 mb-0">
				<label class="control-label mb-1">文字</label>
				<div class="input-group">
					<input autofocus="" type="text" id="input-text" value="${text}" placeholder="请输入文字" class="form-control" autocomplete="off">
				</div>
			</div>
			<div class="form-group p-1 mb-0">
				<label class="control-label mb-1">运势百分比</label>
				<div class="input-group">
					<input autofocus="" type="number" id="input-width" value="${width}" placeholder="请输入数值" class="form-control" autocomplete="off">
					<span class="input-group-text"><i class="mdi mdi-percent-outline"></i></span>
				</div>
			</div>
		`,
		buttons: {
			submit: {
				text: '提交',
				btnClass: 'btn-primary',
				action: function () {
					let that = this.$content

					const text = that.find('#input-text').val()
					const width = that.find('#input-width').val()
					
					if (Number(width) < 0 || Number(width) > 100) {
						$.alert({
							title: '',
							content: '百分比不得小于0或大于100',
							type: 'orange'
						})
						return false
					}

					const data = {
						id,
						text,
						width
					}

					if (!$.trim(id) || !$.trim(text) || !$.trim(width)) {
						$.alert({
							title: '',
							content: '参数不得为空',
							type: 'orange'
						})
						return false
					}
					
					$.ajax({
						url: fortuneApiPath + 'set',
						type: 'POST',
						data,
						success: function (response) {
							const { code, msg } = response
							if (code !== 200) {
								$.alert({
									title: '',
									content: msg,
									type: 'orange'
								})
								return
							}
							$.alert({
								title: '',
								content: '更新成功',
								type: 'green'
							})

							getFortune()
						}
					})
				}
			},
			'取消': function () { }
		}
	})
}

$(document).ready(async function (e) {
	$('input, textarea').attr('autocomplete', 'off')
	getModules()
	getRest()
	getFortune()
})